// © 2009 Microsoft Corporation.  All rights reserved.
#region Namespaces
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.InformationSecurity.ISRM.TaskManagment.Classes;
using Microsoft.InformationSecurity.ISRM.TaskManagment.TaskMessages;
#endregion

namespace Microsoft.InformationSecurity.ISRM.TaskManagment.Classes
{
    /// <summary>
    /// Implements methods to maintain groups in the database.
    /// </summary>
    public static class Groups
    {
        /// <summary>
        /// Add a Task Group into the syatem database.
        /// </summary>
        /// <param name="group">New group</param>
        /// <returns>Group ID</returns>
        public static int AddGroup(Group group)
        {
            int groupID;
            Database db = null;
            try
            {                
                if (group == null)
                    throw new ArgumentNullException("group");

                if (string.IsNullOrEmpty(group.Name))
                    throw new ArgumentNullException("GroupName", TaskMessages.Messages.GetServiceMessage("GroupNameNotNull"));

                ValidationResults validationResults = Validation.Validate<Group>(group, "GroupBasicRules");

                if (validationResults.IsValid == false)
                {
                    throw new ArgumentException(TaskMessages.Messages.GetServiceMessage("GroupValidationFailed"));
                }
                groupID = -1;

                db = DatabaseFactory.CreateDatabase("ISRMDB");
                SqlCommand createCatCommand = new SqlCommand("ISRM_spInsertTaskGroup");
                createCatCommand.CommandType = CommandType.StoredProcedure;
                createCatCommand.Parameters.Add("@groupName", SqlDbType.NVarChar, 100);
                createCatCommand.Parameters.Add("@username", SqlDbType.NVarChar, 50);
                createCatCommand.Parameters.Add("@groupID", SqlDbType.Int);
                createCatCommand.Parameters["@groupName"].Value = group.Name;
                createCatCommand.Parameters["@username"].Value = group.LastUpdatedBy;
                createCatCommand.Parameters["@groupID"].Direction = ParameterDirection.Output;
                createCatCommand.Parameters.Add("@personID", SqlDbType.Int).Value = group.PersonID;

                db.ExecuteNonQuery(createCatCommand);
                groupID = (int)createCatCommand.Parameters["@groupID"].Value;
            }
            catch (SqlException sqlEx)
            {
                string dbErrorMessage = Messages.GetDatabaseMessage(sqlEx.Message);
                if (!string.IsNullOrEmpty(dbErrorMessage))
                {
                    throw new ArgumentException(dbErrorMessage);
                }
                else
                    throw;

            }
            catch { throw; }
            finally
            {
                if (db != null)
                    db = null;
            }
            return groupID;
        }


        /// <summary>
        /// Updates a group in the database.
        /// </summary>
        /// <param name="group">Updated Group</param>
        public static void UpdateGroup(Microsoft.InformationSecurity.ISRM.TaskManagment.Classes.Group group)
        {
            if (group == null)
                throw new ArgumentNullException("group");

            if (string.IsNullOrEmpty(group.Name))
                throw new ArgumentNullException("GroupName", TaskMessages.Messages.GetServiceMessage("GroupNameNotNull"));

            ValidationResults validationResults = Validation.Validate<Group>(group, "GroupBasicRules");

            if (validationResults.IsValid == false)
            {
                throw new ArgumentException(TaskMessages.Messages.GetServiceMessage("GroupValidationFailed"));
            }
            Database db = null;
            try
            {
                db = DatabaseFactory.CreateDatabase("ISRMDB");
                db.ExecuteNonQuery("ISRM_spUpdateTaskGroup", group.ID, group.Name, group.LastUpdatedBy, group.PersonID);
            }
            catch (SqlException sqlEx)
            {
                string dbErrorMessage = Messages.GetDatabaseMessage(sqlEx.Message);
                if (!string.IsNullOrEmpty(dbErrorMessage))
                {
                    throw new ArgumentException(dbErrorMessage);
                }
                else
                    throw;

            }
            catch { throw; }
            finally
            {
                if (db != null)
                    db = null;
            }
        }

        /// <summary>
        /// Deletes a group from the database.
        /// </summary>
        /// <param name="groupID">Group ID</param>
        /// <param name="userID">User ID</param>
        /// <param name="personID">personID</param>
        public static void DeleteGroup(int groupID, string userID, int personID)
        {
            if (groupID <= 0)
                throw new ArgumentNullException("groupID");


            Database db = null;
            try
            {
                db = DatabaseFactory.CreateDatabase("ISRMDB");
                db.ExecuteNonQuery("ISRM_spDeleteTaskGroup", groupID, userID, personID);
            }
            catch (SqlException sqlEx)
            {
                string dbErrorMessage = Messages.GetDatabaseMessage(sqlEx.Message);
                if (!string.IsNullOrEmpty(dbErrorMessage))
                {
                    throw new ArgumentException(dbErrorMessage);
                }
                else
                    throw;

            }
            catch { throw; }
            finally
            {
                if (db != null)
                    db = null;
            }
        }

        /// <summary>
        /// Returns the list of active groups
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
        public static ICollection<Group> GetActiveGroups()
        {
            Database db = null;
            IDataReader dbReader = null;
            List<Group> lstGroups = new List<Group>();
            try
            {
                db = DatabaseFactory.CreateDatabase("ISRMDB");
                dbReader = (SqlDataReader)db.ExecuteReader(CommandType.StoredProcedure, "ISRM_spGetActiveTaskGroups");
                while (dbReader.Read())
                {
                    Group group = new Group();
                    group.ID = dbReader.GetInt32(0);
                    group.Name = dbReader.GetString(1);
                    group.LastUpdatedBy = dbReader.GetString(2);
                    group.LastUpdatedDate = dbReader.GetDateTime(3);
                    group.TaskCount = dbReader.GetInt32(4);
                    group.Active = true;

                    lstGroups.Add(group);
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (dbReader != null)
                {
                    dbReader.Close();
                    dbReader = null;
                }
                if (db != null)
                    db = null;
            }
            return lstGroups;
        }

        /// <summary>
        /// Returns the list of active groups
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
        public static ICollection<Group> GetAllGroups()
        {
            Database db = null;
            IDataReader dbReader = null;
            List<Group> lstGroups = new List<Group>();
            try
            {
                db = DatabaseFactory.CreateDatabase("ISRMDB");
                dbReader = (SqlDataReader)db.ExecuteReader(CommandType.StoredProcedure, "ISRM_spGetAllTaskGroups");
                while (dbReader.Read())
                {
                    Group group = new Group();
                    group.ID = dbReader.GetInt32(0);
                    group.Name = dbReader.GetString(1);
                    group.LastUpdatedBy = dbReader.GetString(2);
                    group.LastUpdatedDate = dbReader.GetDateTime(3);
                    group.TaskCount = dbReader.GetInt32(4);
                    group.Active = dbReader.GetBoolean(5);

                    lstGroups.Add(group);
                }
            }
            catch { throw; }
            finally
            {

                if (dbReader != null)
                {
                    dbReader.Close();
                    dbReader = null;
                }
                if (db != null)
                    db = null;
            }
            return lstGroups;
        }
    }
}
